package com.mxpio.erp.equipment.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.mxpio.erp.common.enums.*;
import com.mxpio.erp.common.equipment.entity.*;
import com.mxpio.erp.common.equipment.service.*;
import com.mxpio.erp.common.inventory.entity.WarehouseOrder;
import com.mxpio.erp.common.inventory.entity.WarehouseOrderLine;
import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.vo.OrderExcuteLineVo;
import com.mxpioframework.common.exception.MBootException;
import com.mxpioframework.common.util.SpringUtil;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.dbconsole.service.DbService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.policy.impl.CrudType;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.message.service.MessageService;
import com.mxpioframework.security.entity.Dept;
import com.mxpioframework.security.entity.User;
import com.mxpioframework.security.service.DeptService;
import com.mxpioframework.security.service.UserService;
import com.mxpioframework.security.util.SecurityUtils;
import com.mxpioframework.system.service.SnRuleService;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 设备维修
 * @Author: jeecg-boot
 * @Date: 2021-09-23
 * @Version: V1.0
 */
@Service
@Slf4j
public class EquipmentRepairServiceImpl extends BaseServiceImpl<EquipmentRepair> implements EquipmentRepairService {

    /**
     * 待派工
     public static final Integer APPLY = 10;
     */
    /**
     * 待维修
     public static final Integer SEND = 20;
     */
    /**
     * 维修中
     public static final Integer REPAIR = 30;
     */
    /**
     * 暂停中
     public static final Integer STOP = 35;
     */
    /**
     * 待验收
     public static final Integer FINISH = 40;
     */
    /**
     * 验收完成
     public static final Integer CHECKED = 50;
     */

    /**
     * 取消/终止
     public static final Integer CANCLE = 90;
     */
    public static final String SOURCE_SG = "手工录入";
    public static final String SOURCE_JJ = "紧急报修";

    public static final String[] channelCodes = {"innerMsg"};

    @Autowired
    private EquipmentRepairOperationService repairOperationService;
    @Autowired
    private EquipmentRepairTransferService repairTransferService;

    @Autowired
    private UserService userService;
    @Autowired
    private EquipmentAreaService equipmentAreaService;
    @Autowired
    private EquipmentEqpBasicsService equipmentService;
    @Autowired
    private EquipmentEqpStatusRecordsService equipmentEqpStatusRecordsService;
//    @Resource
//    private ActivitiInstanceController activitiInstanceController;
    @Autowired
    private EquipmentPersonGroupDetailService equipmentPersonGroupDetailService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private EquipmentRepairOperationService equipmentRepairOperationService;

    @Autowired
    private EquipmentRepairAssistantsService equipmentRepairAssistantsService;

    @Resource
    private MessageService messageService;//消息

    @Autowired
    private FaultTypeService faultTypeService;

    @Autowired
    private DbService dbService;

    /*@Value("${dingtalk.executeDetailUrl}")
    private String executeDetailUrl;
    @Value("${dingtalk.applyDetailUrl}")
    private String applyDetailUrl;*/
public Page<EquipmentRepair> getTpmRepairIPage(Criteria criteria, Pageable page, String flag, String applyStart, String applyEnd, String planRepairStart, String planRepairEnd, String failureTime, HttpServletRequest req) {
    User sysUser = SecurityUtils.getLoginUser();//获取登陆人的信息
    String username = sysUser.getUsername();
//    Linq linq = JpaUtil.linq(EquipmentRepair.class).where(criteria);
    //申请工单关联工单
    if ("apply".equals(flag)) {
        criteria.addCriterion("applyId",Operator.EQ, username)
                .or().addCriterion("createBy",Operator.EQ, username);
    } else if ("send".equals(flag)) {//派工模式
        criteria.and().addCriterion("dispatchMode",Operator.EQ, "assign")
                .addCriterion("recePersonId",Operator.EQ, username)
                .addCriterion("repairStatus",Operator.EQ, 10);
    } else if ("grab".equals(flag)) { //抢单模式
        criteria.and().addCriterion("dispatchMode",Operator.EQ, "grab")
                .addCriterion("repairStatus",Operator.EQ, 10);
        //获取当前用户的所属部门
        Set<String> deps = deptService.getDeptKeysByUser(sysUser.getUsername(),"id");
        //todo wait groups
        //获取当前用户所属的群组
        List<String> groups = equipmentPersonGroupDetailService.selectByUsername(sysUser.getUsername());
//        List<String> departs = deps.stream().map(a -> a.getId()).collect(Collectors.toList());
        groups.addAll(deps);
        criteria.addCriterion("orgId",Operator.IN, groups);
//                .end();
    } else if ("toRepair".equals(flag)) {
        criteria.and().addCriterion("distributePersonId",Operator.EQ, username)//查询当前用户为执行人
                .addCriterion("repairStatus",Operator.EQ, 20) //查询状态为20
                ;
    } else if ("repairing".equals(flag)) {
        criteria.and().addCriterion("distributePersonId",Operator.EQ,  username)//查询当前用户为执行人
                .addCriterion("repairStatus",Operator.EQ, 30) //查询状态为30
                ;
    } else if ("stop".equals(flag)) {
        criteria.and().addCriterion("distributePersonId",Operator.EQ, username)//查询当前用户为执行人
                .addCriterion("repairStatus",Operator.EQ, 35) //查询状态为35
                ;
    } else if ("repair".equals(flag)) {
       int[] status = {20, 30, 35} ;
        criteria.and().addCriterion("distributePersonId",Operator.EQ, username)//查询当前用户为执行人
                .addCriterion("repairStatus",Operator.IN, status)  //查询状态为20,30,35
                ;
    } else if ("check".equals(flag)) {
        criteria.and().addCriterion("repairStatus",Operator.EQ, 40)  //查询状态为40
                ;
        //查询当前用户为申请人或者部门负责人
        criteria.and().addCriterion("applyId",Operator.EQ, username)
                .or().addCriterion("recePersonId",Operator.EQ,username)
                ;
    } else if ("record".equals(flag)) {

        //查询当前用户为申请人或者部门负责人
        criteria.and().addCriterion("applyId",Operator.EQ,  username)
                .or().addCriterion("recePersonId",Operator.EQ, username)
                .or().addCriterion("createBy",Operator.EQ, username)
                ;
        criteria.and().addCriterion("repairStatus",Operator.EQ,  50)  //查询状态为50
                ;
    } else if ("repairOverdue".equals(flag)) {//逾期未执行
        int[] status = {20, 30, 35} ;
        //查询状态为20,30,35
        criteria.and().addCriterion("distributePersonId",Operator.EQ, username)//查询当前用户为执行人
                .addCriterion("repairStatus",Operator.IN,status)  //查询状态为20,30,35
                .addCriterion("planRepairEndDate",Operator.LT,DateUtil.now())//当前时间大于预计完成时间的未完工工单
                ;
    } else if ("overdueFinish".equals(flag)) {//逾期完成
        int[] status = {40, 50} ;
        //查询状态为40, 50
        criteria.and().addCriterion("repairStatus",Operator.IN, status)  //查询状态为20,30,35
                .addCriterion("planRepairEndDate",Operator.LT,DateUtil.now())//当前时间大于预计完成时间的未完工工单
                .addCriterion("overFlag",Operator.EQ, 1)//当前时间大于预计完成时间的未完工工单
                ;
        //查询当前用户为相关人
        criteria.and().addCriterion("applyId",Operator.EQ, username)
                .or().addCriterion("recePersonId",Operator.EQ,username)
                .or().addCriterion("createBy",Operator.EQ,username)
                .or().addCriterion("distributePersonId",Operator.EQ,username)
                .or().addCriterion("checkUser",Operator.EQ,username)
                ;

    }
    /**  时间查询开始 */
    //查询申请时间大于等于
    if (StringUtils.isNotBlank(applyStart)) {
         criteria.and().addCriterion("applyTime",Operator.GE,applyStart + " 00:00:00")
                ;
    }
    //查询申请时间小于等于
    if (StringUtils.isNotBlank(applyEnd)) {
        criteria.and().addCriterion("applyTime",Operator.LE,applyEnd + " 23:59:59")
                ;
    }
    //查询计划开始时间大于等于
    if (StringUtils.isNotBlank(planRepairStart)) {
        criteria.and().addCriterion("planRepairStartDate",Operator.GE,planRepairStart + " 00:00:00")
                ;
    }
    //查询计划结束时间小于等于
    if (StringUtils.isNotBlank(planRepairEnd)) {
        criteria.and().addCriterion("planRepairEndDate",Operator.LE,planRepairEnd + " 23:59:59")
                ;
    }
    //查询故障时间
    if (StringUtils.isNotBlank(failureTime)) {
        criteria.and().addCriterion("failureDate",Operator.LE,failureTime )
                ;
    }


    /**  时间查询结束 */
//    queryWrapper.orderByDesc("update_time", "create_time");
    return JpaUtil.linq(EquipmentRepair.class).where(criteria).paging(page);
//    return this.listPage(EquipmentRepair.class, page, criteria);
}


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String bizNo) {
        EquipmentRepair bean = this.getById(EquipmentRepair.class,bizNo);
        if (bean == null) {
            throw new MBootException("未找到对应实体！");
        }
        if (!EquipmentEnums.RepairStatus.APPLY.getCode().equals(bean.getRepairStatus())){
            throw new MBootException(("仅待派工状态下可以执行删除操作！"));
        }
        this.delete(EquipmentRepair.class, bizNo);
        //删除子表
        JpaUtil.lind(EquipmentRepairAssistants.class).equal("bizNo",bizNo).delete();
        JpaUtil.lind(EquipmentRepairEvaluateDetail.class).equal("bizNo",bizNo).delete();
        JpaUtil.lind(EquipmentRepairOperation.class).equal("bizNo",bizNo).delete();
        JpaUtil.lind(EquipmentRepairPickupLine.class).equal("bizNo",bizNo).delete();
        JpaUtil.lind(EquipmentRepairProgress.class).equal("bizNo",bizNo).delete();
        JpaUtil.lind(EquipmentRepairTransfer.class).equal("bizNo",bizNo).delete();
        JpaUtil.lind(EquipmentRepairUrgeLine.class).equal("bizNo",bizNo).delete();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> bizNoList) {
        Criteria c = Criteria.create().addCriterion("bizNo", Operator.IN, bizNoList);
        List<EquipmentRepair> dbList = this.list(EquipmentRepair.class, c);
        if (!dbList.isEmpty()){
            for (EquipmentRepair repair:dbList){
                if (!EquipmentEnums.RepairStatus.APPLY.getCode().equals(repair.getRepairStatus())){
                    throw new MBootException(("存在非待派工状态的工单【"+repair.getBizNo()+"】，仅待派工状态下可以执行删除操作！"));
                }
            }
        }
        this.deleteBatch(EquipmentRepair.class, c);
        //删除子表
        JpaUtil.lind(EquipmentRepairAssistants.class).in("bizNo",bizNoList).delete();
        JpaUtil.lind(EquipmentRepairEvaluateDetail.class).in("bizNo",bizNoList).delete();
        JpaUtil.lind(EquipmentRepairOperation.class).in("bizNo",bizNoList).delete();
        JpaUtil.lind(EquipmentRepairPickupLine.class).in("bizNo",bizNoList).delete();
        JpaUtil.lind(EquipmentRepairProgress.class).in("bizNo",bizNoList).delete();
        JpaUtil.lind(EquipmentRepairTransfer.class).in("bizNo",bizNoList).delete();
        JpaUtil.lind(EquipmentRepairUrgeLine.class).in("bizNo",bizNoList).delete();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRepair(EquipmentRepair equipmentRepair) {
        if (equipmentRepair.getCrudType().name().equals("UPDATE")){
            equipmentRepair.setCrudType(CrudType.SAVE);
        }
        //设置工单编码
        //equipmentRepair.setOrderCode(OrderNumberUtil.getCode("WX"));
        //设置状态
        equipmentRepair.setRepairStatus(EquipmentEnums.RepairStatus.APPLY.getCode());
        User loginUser = SecurityUtils.getLoginUser();
        //未选择申请用户时设置为当前用户
        if (StringUtils.isEmpty(equipmentRepair.getApplyId())) {
            equipmentRepair.setApplyId(loginUser.getNickname());
        }
        //未选择申请时间时设置为当前时间
        if (equipmentRepair.getApplyTime() == null) {
            equipmentRepair.setApplyTime(new Date());
        }

        //todo
        //选择为设备时调整设备状态 为40（维保中）
        /*if ("eqp".equals(equipmentRepair.getTargetType())) {
            EquipmentEqpBasics eqpBasics = equipmentService.getById(EquipmentEqpBasics.class, equipmentRepair.getTargetId());
            //更新上一条记录的下一个操作时间
            equipmentEqpStatusRecordsService.saveRecordAndUpdatePreRecord(eqpBasics,40,"设备维修");
            //变更设备状态
            eqpBasics.setStatus(40);
            equipmentService.update(eqpBasics);

        }*/
        //区域时设置区域名称，编码
        /*if ("area".equals(equipmentRepair.getTargetType())) {
            EquipmentArea equipmentArea = equipmentAreaService.getById(EquipmentArea.class,equipmentRepair.getTargetId());
            String name = equipmentAreaService.getParentAllNameByPid(equipmentArea.getPid());
            equipmentRepair.setTargetName(name + " " + equipmentArea.getAreaName());
            equipmentRepair.setTargetCode(equipmentArea.getAreaCode());
        }*/
        //设置申请人工号
        //User sysUser = userService.findByName(equipmentRepair.getApplyId());
        //equipmentRepair.setApplyNo(sysUser.getUsername());
        if (equipmentRepair.getEmergencyFlag() != null && equipmentRepair.getEmergencyFlag() == 1) {
            equipmentRepair.setSourceType(SOURCE_JJ);
        } else {
            //设置为非紧急工单
            equipmentRepair.setEmergencyFlag(0);
            //设置工单来源 --- 默认为手动输入
            if (StringUtils.isEmpty(equipmentRepair.getSourceType())) {
                equipmentRepair.setSourceType(SOURCE_SG);
            }
        }
        equipmentRepair.setIsFUWork(CommonEnums.YesNo.NO.getCode());
        equipmentRepair.setShutdownTime(0L);
        //保存
        this.save(equipmentRepair);
        //添加操作历史
        insertOperate(equipmentRepair.getBizNo(), "维修申请", "维修申请");
        //发送消息
        /*String faultTypeCode = equipmentRepair.getFaultTypeCode();
        if (StringUtils.isNotBlank(faultTypeCode)){
            FaultType faultType = faultTypeService.getById(FaultType.class, faultTypeCode);
            String groupId = faultType.getGroupId();
            EquipmentPersonGroup personGroup = JpaUtil.getOne(EquipmentPersonGroup.class,groupId);
            StringBuilder thirdUserIdsStr = new StringBuilder();
            if (personGroup!=null){
                List<String> userIds = equipmentPersonGroupDetailService.selectUserIdByGroupId(personGroup.getId());
                if (userIds.size()>0){
                    for (String userId:userIds){
                        User dbUser = JpaUtil.getOne(User.class, userId);
                        if (dbUser!=null&&StringUtils.isNotBlank(dbUser.getThirdId())){
                            thirdUserIdsStr.append(dbUser.getThirdId()).append(",");
                        }
                    }
                }
            }

            if (StringUtils.isNotBlank(thirdUserIdsStr)){
                String substring = thirdUserIdsStr.substring(0, thirdUserIdsStr.lastIndexOf(","));
                DingTalkMessagePojo dingTalkMessagePojo = new DingTalkMessagePojo();
                dingTalkMessagePojo.setMsgtype(DingTalkEnums.MsgType.LINK.getCode());
                LinkTypeContent linkTypeContent = new LinkTypeContent();
                linkTypeContent.setMessageUrl(executeDetailUrl+equipmentRepair.getOrderCode());
                linkTypeContent.setPicUrl("@lADOADmaWMzazQKA");
                String title = "维修申请处理";
                linkTypeContent.setTitle(title);
                linkTypeContent.setText("用户新增了维修申请，请及时处理，单号："+equipmentRepair.getOrderCode());
                dingTalkMessagePojo.setLink(linkTypeContent);
                //log.error("thirdUserIdsStr:"+substring+";"+JSONObject.toJSONString(dingTalkMessagePojo));
                messageService.sendMessage(channelCodes,"",substring.split(","),title, JSONObject.toJSONString(dingTalkMessagePojo));
            }
        }*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRepairById(EquipmentRepair equipmentRepair) {
        //设置申请人工号
        //User sysUser = userService.findByName(equipmentRepair.getApplyId());
        //equipmentRepair.setApplyNo(sysUser.getUsername());
        //区域时设置区域名称，编码
        EquipmentRepair one = this.getById(EquipmentRepair.class, equipmentRepair.getBizNo());
        if(one.getRepairStatus() != EquipmentEnums.RepairStatus.APPLY.getCode()){
            throw new MBootException("非待派工状态不可编辑！");
        }
        if ("area".equals(equipmentRepair.getTargetType())) {
            EquipmentArea equipmentArea = equipmentAreaService.getById(EquipmentArea.class,equipmentRepair.getTargetId());
            //获取该区域的上级区域的名称
            String name = equipmentAreaService.getParentAllNameByPid(equipmentArea.getPid());
            equipmentRepair.setTargetName(name +"/"+ equipmentArea.getAreaName());
            equipmentRepair.setTargetCode(equipmentArea.getAreaCode());
            one.setTargetName(equipmentRepair.getTargetName());
            one.setTargetCode(equipmentRepair.getTargetCode());
        }
        //选择为设备时调整设备状态 为40（维保中）
        /*if ("eqp".equals(equipmentRepair.getTargetType())) {
            EquipmentEqpBasics eqpBasics = equipmentService.getById(EquipmentEqpBasics.class, equipmentRepair.getTargetId());
            //更新上一条记录的下一个操作时间
            equipmentEqpStatusRecordsService.saveRecordAndUpdatePreRecord(eqpBasics,40,"设备维修");
            //变更设备状态
            eqpBasics.setStatus(40);
            equipmentService.update(eqpBasics);
            equipmentRepair.setTargetCode(eqpBasics.getEqpCode());
            equipmentRepair.setTargetName(eqpBasics.getEqpName());

        }*/
        one.setTargetId(equipmentRepair.getTargetId());
        one.setBizType(equipmentRepair.getBizType());
        one.setApplyHalt(equipmentRepair.getApplyHalt());
        one.setFailureDate(equipmentRepair.getFailureDate());
        one.setApplyId(equipmentRepair.getApplyId());
        one.setChkPersonPhone(equipmentRepair.getChkPersonPhone());
        one.setExistingProblems(equipmentRepair.getExistingProblems());
        one.setPic(equipmentRepair.getPic());
        one.setAttachFile(equipmentRepair.getAttachFile());
        one.setIsBottleneck(equipmentRepair.getIsBottleneck());
        this.update(one);
    }

    /**
     * 派单操作
     * @param tpmRepair
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendRepairById(EquipmentRepair tpmRepair) {
        EquipmentRepair bean = this.getById(EquipmentRepair.class,tpmRepair.getBizNo());
        if (StringUtils.isEmpty(tpmRepair.getBizNo()) || bean == null) {
            throw new MBootException("id为空或者未找到对应实体！");
        }

        if ( bean.getRepairStatus() != EquipmentEnums.RepairStatus.APPLY.getCode()) {
            throw new MBootException("非待派工状态不可派工！");
        }
        if (bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            throw new MBootException(("单据已取消，不允许此操作！"));
        }
        bean.setDispatchMode("assign");
        //派工人员信息
        bean.setDistributePersonId(tpmRepair.getDistributePersonId());
        bean.setDistributeTime(new Date());

        //设置计划开始结束时间
        bean.setPlanRepairEndDate(tpmRepair.getPlanRepairEndDate());
        bean.setPlanRepairStartDate(tpmRepair.getPlanRepairStartDate());
        bean.setHourRation(tpmRepair.getHourRation());//工时定额（计划工时）
        //改变状态---设置为派工状态
        bean.setRepairStatus(EquipmentEnums.RepairStatus.SEND.getCode());
        this.update(bean);
        //添加操作记录
        insertOperate(tpmRepair.getBizNo(), "维修派工", "维修派工");

    }

    /**
     * 抢单操作
     * @param tpmRepair
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void grabRepairById(EquipmentRepair tpmRepair) {
        EquipmentRepair bean = this.getById(EquipmentRepair.class,tpmRepair.getBizNo());
        if (StringUtils.isEmpty(tpmRepair.getBizNo()) || bean == null) {
            throw new MBootException("id为空或者未找到对应实体！");
        }
        if (bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            throw new MBootException(("单据已取消，不允许此操作！"));
        }
        bean.setDispatchMode("grab");
        User loginUser = SecurityUtils.getLoginUser();
        //执行人员信息
        bean.setDistributePersonId(loginUser.getUsername());
        bean.setDistributeTime(new Date());

        //设置计划开始结束时间
        bean.setPlanRepairEndDate(tpmRepair.getPlanRepairEndDate());
        bean.setPlanRepairStartDate(tpmRepair.getPlanRepairStartDate());
        bean.setHourRation(tpmRepair.getHourRation());//工时定额（计划工时）
        //改变状态---设置为派工状态
        bean.setRepairStatus(EquipmentEnums.RepairStatus.SEND.getCode());
        this.update(bean);
        //添加操作记录
        insertOperate(tpmRepair.getBizNo(), "维修抢单", "维修抢单");

    }


    /**
     * 添加操作记录
     *
     * @param repairId 维修ID
     * @param operate  操作
     * @param reason   原因（主要用具回退填写原因）
     */
    private void insertOperate(String repairId, String operate, String reason) {
        EquipmentRepairOperation operation = new EquipmentRepairOperation();   //对操作历史进行赋值操作
        //设置维修ID
        operation.setBizNo(repairId);
        //设置操作名称
        operation.setOperate(operate);
        //设置操作原因
        operation.setReason(reason);
        //设置操作时间
        operation.setOperateTime(new Date());
        //获取当前登录用户
        User loginUser = SecurityUtils.getLoginUser();
        //设置操作人
        operation.setOperator(loginUser.getNickname() + "/" + loginUser.getUsername());
        //保存
        repairOperationService.save(operation);
    }


    /**
     * 添加操作记录
     *
     * @param repairId 维修ID
     * @param operate  操作
     * @param reason   原因（主要用具回退填写原因）
     * @param time     时间戳
     */
    private void insertOperate(String repairId, String operate, String reason, long time) {
        EquipmentRepairOperation operation = new EquipmentRepairOperation();
        //设置维修ID
        operation.setBizNo(repairId);
        //设置操作名称
        operation.setOperate(operate);
        //设置操作原因
        operation.setReason(reason);
        //设置操作时间
        operation.setOperateTime(new Date(time));
        //获取当前登录用户
        User loginUser = SecurityUtils.getLoginUser();
        //设置操作人
        operation.setOperator(loginUser.getNickname() + "/" + loginUser.getUsername());
        //保存
        repairOperationService.save(operation);
    }

    /**
     * 改派
     *
     * @param reason
     * @param username
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reSendRepairById(String reason, String username, String bizNo) {
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,bizNo);
        if (StringUtils.isEmpty(bizNo) || tpmRepair == null) {
            throw new MBootException("id为空或者未找到对应实体！");
        }

        if (tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            throw new MBootException(("单据已取消，不允许此操作！"));
        }
        //设置改派记录
        EquipmentRepairTransfer transfer = new EquipmentRepairTransfer();
        transfer.setBizNo(bizNo);
        User user = userService.findByName(username);
        transfer.setNewExecutor(user.getNickname() + "/" + user.getUsername());
        //设置旧的人员信息
        if (tpmRepair.getDistributePersonId() != null) {
            User oldUser = userService.findByName(tpmRepair.getDistributePersonId());
            transfer.setOldExecutor(oldUser.getNickname() + "/" + oldUser.getUsername());
        }
        transfer.setReason(reason);
        transfer.setType("维修执行");
        transfer.setTransferTime(new Date());
        repairTransferService.save(transfer);

        //设置新的改派人
        tpmRepair.setDistributePersonId(username);
        this.update(tpmRepair);
        //设置操作记录
        insertOperate(bizNo, "维修改派", reason);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void start(EquipmentRepair equipmentRepair) {
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,equipmentRepair.getBizNo());
        if (tpmRepair == null || tpmRepair.getRepairStatus() != EquipmentEnums.RepairStatus.SEND.getCode()) {
            throw new MBootException("实体未找到或非未开始维修状态！");
        }
        if (tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            throw new MBootException(("单据已取消，不允许此操作！"));
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.REPAIR.getCode());
        tpmRepair.setActualStartDate(new Date());
        tpmRepair.setPlanRepairStartDate(equipmentRepair.getPlanRepairStartDate());
        tpmRepair.setPlanRepairEndDate(equipmentRepair.getPlanRepairEndDate());
        tpmRepair.setOrderStatus(EquipmentEnums.RepairOrderStatus.EXEC.getCode());//增加工单状态
        this.update(tpmRepair);

        //设置操作记录
        insertOperate(equipmentRepair.getBizNo(), "维修开始", "维修开始");
    }

    /**
     * 评价操作
     * @param equipmentRepair
     * @return
     */
    @Override
    @Transactional
    @Deprecated
    public Result<?> evaluate(EquipmentRepair equipmentRepair) {
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,equipmentRepair.getBizNo());
        if (tpmRepair == null ) {
            return Result.error("未找到实体对象");
        }
        if (!tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.EVA.getCode()) ){
            return Result.error("仅待评价状态可以评价！");
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.SUPERVISOR.getCode());
        tpmRepair.setEvaluateDate(new Date());
        tpmRepair.setEvaluateStar(equipmentRepair.getEvaluateStar());
        //tpmRepair.setIsUsable(equipmentRepair.getIsUsable());//由check环节赋值更新
        tpmRepair.setEvaluateContent(equipmentRepair.getEvaluateContent());
        tpmRepair.setEvaluateUser(SecurityUtils.getLoginUser().getUsername());
        tpmRepair.setEvaluateImg(equipmentRepair.getEvaluateImg());
      //  tpmRepair.setOrderStatus(EquipmentEnums.RepairStatus.ZIPING.getCode());//增加工单状态
        this.update(tpmRepair);

        //设置操作记录
        insertOperate(equipmentRepair.getBizNo(), "评分", "评分");
        return Result.OK(tpmRepair);
    }

    @Override
    @Transactional
    public Result<?> statement(EquipmentRepair equipmentRepair) {
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,equipmentRepair.getBizNo());
        if (tpmRepair == null ) {
            return Result.error("未找到实体对象");
        }
        if (!tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.REPAIR.getCode()) ){
            return Result.error("仅维修中状态可以结单！");
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.EVA.getCode());
        tpmRepair.setMalfunctionReason(equipmentRepair.getMalfunctionReason());
        tpmRepair.setMalfunctionHandling(equipmentRepair.getMalfunctionHandling());
        tpmRepair.setMalfunctionImg(equipmentRepair.getMalfunctionImg());
        this.update(tpmRepair);

        insertOperate(equipmentRepair.getBizNo(), "结单", "结单");

        //发送消息
        /*User dbUser = JpaUtil.getOne(User.class, equipmentRepair.getCreateBy());
        if (dbUser!=null&&StringUtils.isNotBlank(dbUser.getThirdId())){
            DingTalkMessagePojo dingTalkMessagePojo = new DingTalkMessagePojo();
            dingTalkMessagePojo.setMsgtype(DingTalkEnums.MsgType.LINK.getCode());
            LinkTypeContent linkTypeContent = new LinkTypeContent();
            linkTypeContent.setMessageUrl(applyDetailUrl+equipmentRepair.getOrderCode());
            linkTypeContent.setPicUrl("@lADOADmaWMzazQKA");
            String title = "维修评价";
            linkTypeContent.setTitle(title);
            linkTypeContent.setText("维修申请已处理完毕，请及时评价，单号："+equipmentRepair.getOrderCode());
            dingTalkMessagePojo.setLink(linkTypeContent);
            //log.error("thirdUserIdsStr:"+dbUser.getThirdId()+";"+JSONObject.toJSONString(dingTalkMessagePojo));
            messageService.sendMessage(channelCodes,"",dbUser.getThirdId().split(","),title, JSONObject.toJSONString(dingTalkMessagePojo));
        }*/
        return Result.OK(tpmRepair);
    }

    @Override
    @Transactional
    public Result<?> cancle(EquipmentRepair equipmentRepair) {
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,equipmentRepair.getBizNo());
        if (tpmRepair == null ) {
            return Result.error("未找到实体对象");
        }
        if (!tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.SEND.getCode())){
            return Result.error("仅待维修状态可以取消！");
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.VETO.getCode());
        this.update(tpmRepair);

        insertOperate(equipmentRepair.getBizNo(), "取消", "取消");
        return Result.OK(tpmRepair);
    }

    @Override
    @Transactional
    public Result<?> veto(EquipmentRepair equipmentRepair) {
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,equipmentRepair.getBizNo());
        if (tpmRepair == null ) {
            return Result.error("未找到实体对象");
        }
        if (!tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.SEND.getCode())){
            return Result.error("仅待维修状态可以否决！");
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.VETO.getCode());
        tpmRepair.setVetoReason(equipmentRepair.getVetoReason());
        this.update(tpmRepair);

        insertOperate(equipmentRepair.getBizNo(), "否决", equipmentRepair.getVetoReason());
        String[] toUsers = {tpmRepair.getCreateBy()};
        //发送站内信
        messageService.sendMessage(channelCodes,SecurityUtils.getLoginUsername(),toUsers,"维修工单被否决","维修工单【"+tpmRepair.getBizNo()+"】被否决，否决原因："+equipmentRepair.getVetoReason()+"。请知悉！具体信息请在工单详情页面查看。");
        return Result.OK(tpmRepair);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finish(EquipmentRepair tpmRepair) {
        EquipmentRepair bean = this.getById(EquipmentRepair.class,tpmRepair.getBizNo());
        if (bean == null || bean.getRepairStatus() != EquipmentEnums.RepairStatus.REPAIR.getCode()) {
            throw new MBootException("实体未找到或未开始维修状态！");
        }
        if (bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            throw new MBootException(("单据已否决，不允许此操作！"));
        }
        //设置工单状态
        bean.setRepairStatus(EquipmentEnums.RepairStatus.CHECK.getCode());//
        bean.setActualEndDate(new Date());
        bean.setOverFlag(0);
        /*//设置是逾期原因
        if (tpmRepair.getOverFlag()!=null && tpmRepair.getOverFlag() == 1) {
            bean.setOverFlag(1);
            bean.setOverdueReason(tpmRepair.getOverdueReason());
        }*/


        // 计算维修工时
        List<EquipmentRepairOperation> tpmRepairOperations = equipmentRepairOperationService.selectByMainId(bean.getBizNo());
        if (!CollectionUtils.isEmpty(tpmRepairOperations)) {
            Date beginStop = new Date();
            long totalWorkTime = DateUtil.between(bean.getActualStartDate(), bean.getActualEndDate(), DateUnit.MINUTE);
            if (totalWorkTime== 0){  //当维修时长小于一分钟时，让它等于1分钟。
                totalWorkTime = 1;
            }
            long totalStopTime = 0;
            // 循环计算暂停时长
            for (int i = 0; i < tpmRepairOperations.size(); i++) {
                if ("维修暂停".equals(tpmRepairOperations.get(i).getOperate())) {
                    beginStop = tpmRepairOperations.get(i).getOperateTime();
                }
                if ("维修暂停结束".equals(tpmRepairOperations.get(i).getOperate())) {
                    totalStopTime += DateUtil.between(beginStop,tpmRepairOperations.get(i).getOperateTime(), DateUnit.MINUTE);
                }
            }
            bean.setWorkMinutes(totalWorkTime - totalStopTime);
            Long workMinutes = bean.getWorkMinutes();
            if (workMinutes>0){
                String hourRation = bean.getHourRation();//计划工时（小时）
                if (StringUtils.isNotBlank(hourRation)&&StringUtils.isNumeric(hourRation)){//判断计划工时
                    BigDecimal hours = new BigDecimal(hourRation);
                    BigDecimal minutes = hours.multiply(new BigDecimal("60"));
                    if (workMinutes>minutes.longValue()){
                        bean.setOverFlag(1);//是否超时根据实际维修工时和计划工时比对
                        bean.setGoBeyondMinutes(workMinutes - minutes.longValue());//计算超时时间
                    }
                }
            }
        }
        this.update(bean);
        //设置操作记录
        insertOperate(bean.getBizNo(), "维修完成", "维修完成");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void stopRepairById(String reason, String id) {
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,id);
        if (tpmRepair == null || tpmRepair.getRepairStatus() != EquipmentEnums.RepairStatus.REPAIR.getCode()) {
            throw  new MBootException("实体未找到或未开始维修状态！");
        }
        if (tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            throw new MBootException(("单据已取消，不允许此操作！"));
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.PAUSE.getCode());
        this.update(tpmRepair);

        //设置操作记录
        insertOperate(id, "维修暂停", reason);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void endStop(String id) {
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,id);
        if (tpmRepair == null || tpmRepair.getRepairStatus() != EquipmentEnums.RepairStatus.PAUSE.getCode()) {
            throw  new MBootException("实体未找到或非暂停状态！");
        }
        if (tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            throw new MBootException(("单据已取消，不允许此操作！"));
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.REPAIR.getCode());
        this.update(tpmRepair);

        //设置操作记录
        insertOperate(id, "维修暂停结束", "维修暂停结束");
    }


    @Override
    @Deprecated
    @Transactional(rollbackFor = Exception.class)
    public void check(String id,Integer evaluateStar, HttpServletRequest request) throws MBootException {
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,id);
        if (tpmRepair == null || tpmRepair.getRepairStatus() != EquipmentEnums.RepairStatus.CHECK.getCode()) {
            throw  new MBootException("实体未找到或非维修完成状态！");
        }
        if (tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            throw new MBootException(("单据已取消，不允许此操作！"));
        }
        //获取当前登录用户
        User loginUser =  SecurityUtils.getLoginUser();
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.ZIPPED.getCode());
        tpmRepair.setCheckTime(new Date());
        tpmRepair.setCheckUser(loginUser.getUsername());
        tpmRepair.setEvaluateStar(evaluateStar);
        this.update(tpmRepair);
        //若为设备时变更设备状态
        /*if ("eqp".equals(tpmRepair.getTargetType())) {
            EquipmentEqpBasics eqpBasics = equipmentService.getById(EquipmentEqpBasics.class,tpmRepair.getTargetId());
            //更新上一条记录的下一个操作时间
            equipmentEqpStatusRecordsService.saveRecordAndUpdatePreRecord(eqpBasics,30,"设备维修完成");
            eqpBasics.setStatus(30); //变更为使用中
            equipmentService.update(eqpBasics);
        }*/
        // 发起签核
//        activitiInstanceController.startOnlInstance(id, "5698109fffc24a468b1ee8e777e6d70f", request);
        //设置操作记录
        insertOperate(id, "维修验收", "维修验收");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reject(String id, String reason)throws MBootException  {
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,id);
        if (tpmRepair == null || tpmRepair.getRepairStatus() != EquipmentEnums.RepairStatus.REPAIR.getCode()) {
            throw  new MBootException("实体未找到或非维修完成状态！");
        }
        if (tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            throw new MBootException(("单据已取消，不允许此操作！"));
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.SEND.getCode());
        this.update(tpmRepair);

        //设置操作记录
        insertOperate(id, "验收回退", reason);
    }

    @Override
    public List<EquipmentRepair> queryRepairingList() {
        Integer[] status = {20,30,35};
        Criteria c = Criteria.create().addCriterion("repairStatus", Operator.IN, status);
        return list(EquipmentRepair.class,c);
    }

    @Override
    @Transactional
    public EquipmentRepair getByOrderCode(String bizNo) {
        return JpaUtil.linq(EquipmentRepair.class).collect("bizNo",EquipmentRepairUrgeLine.class,"bizNo").equal("bizNo", bizNo).findOne();
    }

    @Override
    @Transactional
    public void signOffBack(String repairId,String reason){
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,repairId);
        if (tpmRepair == null || tpmRepair.getRepairStatus() != EquipmentEnums.RepairStatus.ZIPPED.getCode()) {
            throw  new MBootException("实体未找到或非维修完成状态！");
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.SEND.getCode());
        this.update(tpmRepair);

        //设置操作记录
        insertOperate(repairId, "签核回退", reason);

        //选择为设备时调整设备状态 为40（维保中）
        /*if ("eqp".equals(tpmRepair.getTargetType())) {
            EquipmentEqpBasics eqpBasics = equipmentService.getById(EquipmentEqpBasics.class,tpmRepair.getTargetId());
            //更新上一条记录的下一个操作时间
            equipmentEqpStatusRecordsService.saveRecordAndUpdatePreRecord(eqpBasics,40,"设备维修");
            //变更设备状态
            eqpBasics.setStatus(40);
            equipmentService.update(eqpBasics);

        }*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executeOffLineData(EquipmentRepair tpmRepair, List<Map> history) {
        EquipmentRepair bean = this.getById(EquipmentRepair.class,tpmRepair.getBizNo());
        if (bean==null){
            throw new MBootException("对象不存在！");
        }
//        tpmRepairMapper.updateById(tpmRepair);
        //查找该维修执行的记录
        List<Map> repairId = history.stream().filter(map -> tpmRepair.getBizNo().equals(map.get("repairId"))).collect(Collectors.toList());
        //保存维修记录
        repairId.stream().forEach(m -> {
            String operate = "维修开始";
            String reason = "维修开始";
            if ("start".equals(m.get("state"))) {
                operate = "维修开始";
                reason = "维修开始";
            } else if ("stop".equals(m.get("state"))) {
                operate = "维修暂停";
                reason = m.get("reason") + "";
            } else if ("resStart".equals(m.get("state"))) {
                operate = "维修暂停结束";
                reason = "维修暂停结束";
            } else if ("finish".equals(m.get("state"))) {
                operate = "维修结束";
                reason = "维修结束";

                // 计算维修工时
                List<EquipmentRepairOperation> tpmRepairOperations = equipmentRepairOperationService.selectByMainId(bean.getBizNo());
                if (!CollectionUtils.isEmpty(tpmRepairOperations)) {
                    Date beginStop = new Date();
                    long totalWorkTime = DateUtil.between(bean.getActualStartDate()==null?tpmRepair.getActualStartDate():bean.getActualStartDate(), tpmRepair.getActualEndDate(), DateUnit.MINUTE);
                    long totalStopTime = 0;
                    // 循环计算暂停时长
                    for (int i = 0; i < tpmRepairOperations.size(); i++) {
                        if ("维修暂停".equals(tpmRepairOperations.get(i).getOperate())) {
                            beginStop = tpmRepairOperations.get(i).getOperateTime();
                        }
                        if ("维修暂停结束".equals(tpmRepairOperations.get(i).getOperate())) {
                            totalStopTime += DateUtil.between(beginStop,tpmRepairOperations.get(i).getOperateTime(), DateUnit.MINUTE);
                        }
                    }
                    tpmRepair.setWorkMinutes(totalWorkTime - totalStopTime);
                    tpmRepair.setWorkMinutes(totalWorkTime - totalStopTime);
                    Long workMinutes = tpmRepair.getWorkMinutes();
                    if (workMinutes>0){
                        String hourRation = tpmRepair.getHourRation();//计划工时（小时）
                        if (StringUtils.isNotBlank(hourRation)&&StringUtils.isNumeric(hourRation)){//判断计划工时
                            BigDecimal hours = new BigDecimal(hourRation);
                            BigDecimal minutes = hours.multiply(new BigDecimal("60"));
                            if (workMinutes>minutes.longValue()){
                                tpmRepair.setOverFlag(1);//是否超时根据实际维修工时和计划工时比对
                                tpmRepair.setGoBeyondMinutes(workMinutes - minutes.longValue());//计算超时时间
                            }
                        }
                    }
                }
            }
            //添加操作记录
            insertOperate(tpmRepair.getBizNo(), operate, reason, (long) m.get("time"));
        });
        this.update(tpmRepair);
    }

    @Override
    @Transactional(readOnly = true)
    public Result<List<EquipmentRepair>> getNowadaysListByAreaid(String areaid) {
        String treeChildIds = equipmentAreaService.queryTreeChildIds(areaid);//获取所有子孙节点
        if (StringUtils.isBlank(treeChildIds)){
            return Result.error("入参未能匹配到对应区域数据");
        }
        String today = DateUtil.format(new Date(), "yyyy-MM-dd");
        Criteria dateCriteria = Criteria.create();
        dateCriteria.addCriterion("createTime",Operator.GE,today);
        //查询所有目标类别为区域的维修单
        List<EquipmentRepair> areaList = JpaUtil.linq(EquipmentRepair.class)
                .equal("targetType", "area")
                .in("targetId", Arrays.asList(treeChildIds.split(",")))
                .where(dateCriteria)
                .list();
        //查询当天所有的
        List<EquipmentRepair> eqpList = JpaUtil.linq(EquipmentRepair.class)
                .equal("targetType", "eqp")
                .exists(EquipmentEqpBasics.class)
                    .equalProperty("id", "targetId")
                    .in("areaId", Arrays.asList(treeChildIds.split(",")))
                .end()
                .where(dateCriteria)
                .list();
        //合并集合
        areaList.addAll(eqpList);
        return Result.OK(areaList);
    }

    @Override
    @Transactional(readOnly = true)
    public Result<List<Map<String, Object>>> getSevendaysCntGroupbyFaultType(String areaid) {
        String treeChildIds = equipmentAreaService.queryTreeChildIds(areaid);//获取所有子孙节点
        if (StringUtils.isBlank(treeChildIds)){
            return Result.error("入参未能匹配到对应区域数据");
        }
        String lastWeek = DateUtil.format(DateUtil.lastWeek(), "yyyy-MM-dd");
        Criteria dateCriteria = Criteria.create();
        dateCriteria.addCriterion("createTime",Operator.GE,lastWeek);
        //查询所有目标类别为区域的维修单
        List<EquipmentRepair> areaList = JpaUtil.linq(EquipmentRepair.class)
                .collect("typeCode",FaultType.class,"faultTypeCode")
                .equal("targetType", "area")
                .in("targetId", Arrays.asList(treeChildIds.split(",")))
                .where(dateCriteria)
                .list();
        //查询七天所有的
        List<EquipmentRepair> eqpList = JpaUtil.linq(EquipmentRepair.class)
                .collect("typeCode",FaultType.class,"faultTypeCode")
                .equal("targetType", "eqp")
                .exists(EquipmentEqpBasics.class)
                .equalProperty("id", "targetId")
                .in("areaId", Arrays.asList(treeChildIds.split(",")))
                .end()
                .where(dateCriteria)
                .list();
        //合并集合
        areaList.addAll(eqpList);
        List<Map<String, Object>> returnList = new ArrayList<>();
        if (areaList.size()>0){
            Map<String, List<EquipmentRepair>> collect = areaList.stream().collect(Collectors.groupingBy(EquipmentRepair::getFaultTypeCode));
            for (String key: collect.keySet()){
                if (StringUtils.isNotBlank(key)){
                    List<EquipmentRepair> equipmentRepairs = collect.get(key);
                    EquipmentRepair equipmentRepair = equipmentRepairs.get(0);
                    Map<String, Object> returnMap = new HashMap<>();
                    FaultType faultType = equipmentRepair.getFaultType();
                    if (faultType!=null){
                        returnMap.put("typeCode",faultType.getTypeCode());
                        returnMap.put("typeName",faultType.getTypeName());
                    }else{
                        returnMap.put("typeCode",key);
                        returnMap.put("typeName",key);
                    }
                    returnMap.put("cnt",equipmentRepairs.size());
                    returnList.add(returnMap);
                }
            }
        }
        return Result.OK(returnList);
    }

    @Override
    @Transactional(readOnly = true)
    public Result<List<Map<String, Object>>> getSevendaysCntGroupbySecondArea(String areaid) {
        EquipmentArea byId = equipmentAreaService.getById(EquipmentArea.class, areaid);
        if (!byId.getPid().equals("0")){
            return Result.error("入参areaid并非一级区域节点，无法正常统计！");
        }
        String lastWeek = DateUtil.format(DateUtil.lastWeek(), "yyyy-MM-dd");
        Criteria dateCriteria = Criteria.create();
        dateCriteria.addCriterion("createTime",Operator.GE,lastWeek);
        List<Map<String, Object>> returnList = new ArrayList<>();
        //拿到所有的二级区域节点
        List<EquipmentArea> secondaryAreaList = JpaUtil.linq(EquipmentArea.class).equal("pid", areaid).list();
        if (secondaryAreaList.size()>0){
            for (EquipmentArea area:secondaryAreaList){
                String secondaryId = area.getId();
                String treeChildIds = equipmentAreaService.queryTreeChildIds(secondaryId);//获取二级下所有子孙节点(包括二级)
                if (StringUtils.isBlank(treeChildIds)){
                    return Result.error("区域ID【"+secondaryId+"】未能匹配到对应区域数据");
                }
                //查询所有目标类别为区域的维修单
                List<EquipmentRepair> areaList = JpaUtil.linq(EquipmentRepair.class)
                        .equal("targetType", "area")
                        .in("targetId", Arrays.asList(treeChildIds.split(",")))
                        .where(dateCriteria)
                        .list();
                //查询七天所有的
                List<EquipmentRepair> eqpList = JpaUtil.linq(EquipmentRepair.class)
                        .equal("targetType", "eqp")
                        .exists(EquipmentEqpBasics.class)
                        .equalProperty("id", "targetId")
                        .in("areaId", Arrays.asList(treeChildIds.split(",")))
                        .end()
                        .where(dateCriteria)
                        .list();
                //合并
                areaList.addAll(eqpList);
                Map<String, Object> returnMap = new HashMap<>();
                returnMap.put("areaCode",area.getAreaCode());
                returnMap.put("areaName",area.getAreaName());
                returnMap.put("cnt",areaList.size());
                returnList.add(returnMap);
            }
        }
        return Result.OK(returnList);
    }

    /*   public static void main(String[] args) {
        String lastWeek = DateUtil.format(DateUtil.lastWeek(), "yyyy-MM-dd");
        String today = DateUtil.format(new Date(), "yyyy-MM-dd");
        System.out.println(lastWeek);
        System.out.println(today);
    }*/

    @Override
    @Transactional  //执行领料，生成领料记录，同时生成对应已确认的通知单及下游待执行的仓单
    public Result<List<EquipmentRepairPickupLine>> executePickUp(EquipmentRepair order, List<OrderExcuteLineVo> lines) {
        if (lines==null||lines.isEmpty()){
            return Result.error("提交数据为空");
        }
        SnRuleService snRuleService = SpringUtil.getBean(SnRuleService.class);
        String expression = order.getBizNo()+"@"+"###";
        Set<String> itemCodeSet = lines.stream().map(OrderExcuteLineVo::getItemCode).collect(Collectors.toSet());
        List<Item> dbItemList = JpaUtil.linq(Item.class).in("itemCode", itemCodeSet).list();
        Map<String,Item> dbItemMap = JpaUtil.index(dbItemList, "itemCode");
        //生成维修单明细（领料明细）
        List<EquipmentRepairPickupLine> pickupLineList = new ArrayList<>();
        for (OrderExcuteLineVo vo:lines){
            String lineNoStr = (String) snRuleService.execute(expression, null);
            String[] split = lineNoStr.split("@");
            EquipmentRepairPickupLine line = new EquipmentRepairPickupLine();
            line.setBizNo(order.getBizNo());
            line.setLineNo(split[1]);
            Item item = dbItemMap.get(vo.getItemCode());
            if (item==null){
                throw new MBootException("提交的领料记录中【"+vo.getItemCode()+"】在系统中不存在！！！");
            }
            //关联物料信息
            line.setItemCode(item.getItemCode());
            line.setItemGroupCode(item.getItemGroupCode());
            line.setDrawingNo(item.getDrawingNo());
            line.setItemName(item.getItemName());
            line.setItemSpec(item.getItemSpec());
            line.setUnitCode(item.getUnitCode());

            line.setWhCode(vo.getWhCode());
            line.setQuantity(vo.getQuantity());
            pickupLineList.add(line);
        }
        JpaUtil.save(pickupLineList);
        List<OrderExcuteLineVo> orderExcuteVos = new ArrayList<>();
        for(EquipmentRepairPickupLine line:pickupLineList){
            OrderExcuteLineVo vo = new OrderExcuteLineVo();
            vo.setBizOrderNo(order.getBizNo());
            vo.setBizOrderlineNo(line.getLineNo());
            vo.setItemCode(line.getItemCode());
            vo.setQuantity(line.getQuantity());
            vo.setWhCode(line.getWhCode());
            orderExcuteVos.add(vo);
        }
        //生成对应通知单
        Map<String, RepairPickupNotice> noticeMap = new HashMap<>();
        Map<String,List<OrderExcuteLineVo>> voMap = new HashMap<>();
        for(OrderExcuteLineVo orderExcuteVo : orderExcuteVos) {
            RepairPickupNotice notice = noticeMap.get(orderExcuteVo.getWhCode());
            if(notice == null) {
                notice = new RepairPickupNotice();

                notice.setBizOrderNo(order.getBizNo());
                notice.setNoticeDate(new Date());
                notice.setWhCode(orderExcuteVo.getWhCode());
                notice.setAccessType(OrderEnums.AccessType.OUT.getCode());//出
                notice.setPickingType(NoticeStatusEnums.NoticeType.SPP_OUT.getCode());//62备件出库
                notice.setNoticeStatus(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode());//直接确认
                noticeMap.put(orderExcuteVo.getWhCode(), notice);
                voMap.put(orderExcuteVo.getWhCode(), new ArrayList<OrderExcuteLineVo>());
            }
            voMap.get(orderExcuteVo.getWhCode()).add(orderExcuteVo);
        }
        // 生成通知单明细
        for(Map.Entry<String,RepairPickupNotice> entry : noticeMap.entrySet()) {
            RepairPickupNotice notice = entry.getValue();
            JpaUtil.save(notice);
            int lineNo = 0;
            for(OrderExcuteLineVo orderExcuteVo : voMap.get(entry.getKey())) {
                lineNo++;

                RepairPickupNoticeLine line = new RepairPickupNoticeLine();
                line.setOriginBizLineNo(orderExcuteVo.getBizOrderlineNo());
                line.setOriginBizNo(orderExcuteVo.getBizOrderNo());
                line.setItemCode(orderExcuteVo.getItemCode());
                line.setNoticeNo(notice.getNoticeNo());
                line.setQuantity(orderExcuteVo.getQuantity());

                line.setLineNo(lineNo+"");
                if (dbItemMap.containsKey(orderExcuteVo.getItemCode())){
                    Item item = dbItemMap.get(orderExcuteVo.getItemCode());
                    line.setItemName(item.getItemName());
                    line.setItemSpec(item.getItemSpec());
                    line.setUnitCode(item.getUnitCode());
                    line.setDrawingNo(item.getDrawingNo());
                }
                JpaUtil.save(line);
                //增加通知单对应的单号和行号
                orderExcuteVo.setNoticeNo(notice.getNoticeNo());
                orderExcuteVo.setNoticeLineNo(line.getLineNo());
            }
        }
        //生成 备件领料出库仓单
        for(Map.Entry<String,RepairPickupNotice> entry : noticeMap.entrySet()) {
            RepairPickupNotice notice = entry.getValue();
            int lineNo = 0;
            WarehouseOrder wo = null;
            for(OrderExcuteLineVo vo : voMap.get(entry.getKey())){
                lineNo++;
                if(wo == null){
                    wo = new WarehouseOrder();
                    wo.setAccessType(notice.getAccessType());
                    wo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                    wo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                    wo.setOrderStatus(OrderStatusEnums.OrderStatus.PLAN.getStatusCode());
                    wo.setOrderDate(new Date());
                    wo.setOriginBizNo(vo.getBizOrderNo());
                    wo.setWhCode(vo.getWhCode());
                    wo.setWoType(notice.getPickingType());
                    wo.setOriginNoticeNo(vo.getNoticeNo());//关联noticeno字段
                    JpaUtil.save(wo);
                }
                WarehouseOrderLine line = new WarehouseOrderLine();
                line.setWhCode(wo.getWhCode());
                line.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                Item item = dbItemMap.get(vo.getItemCode());
                line.setItemCode(vo.getItemCode());
                line.setItemGroupCode(item.getItemGroupCode());
                line.setItemName(item.getItemName());
                line.setItemSpec(item.getItemSpec());
                line.setUnitCode(item.getUnitCode());
                line.setDrawingNo(item.getDrawingNo());
                line.setQuantity(vo.getQuantity());
                line.setBizNo(wo.getBizNo());
                line.setLineNo(lineNo+"");
                line.setOriginBizNo(vo.getBizOrderNo());
                line.setOriginBizLineNo(vo.getBizOrderlineNo());
                line.setSort(vo.getSort());
                line.setOriginNoticeNo(vo.getNoticeNo());
                line.setOriginNoticeLineNo(vo.getNoticeLineNo());
                JpaUtil.save(line);
            }
        }
        return Result.OK(pickupLineList);
    }

    @Override
    @Transactional
    public Result<Object> executeReturn(EquipmentRepair order, List<OrderExcuteLineVo> lines) {
        if (lines==null||lines.isEmpty()){
            return Result.error("提交数据为空");
        }
        Set<String> itemCodeSet = lines.stream().map(OrderExcuteLineVo::getItemCode).collect(Collectors.toSet());
        List<Item> dbItemList = JpaUtil.linq(Item.class).in("itemCode", itemCodeSet).list();
        Map<String,Item> dbItemMap = JpaUtil.index(dbItemList, "itemCode");
        //生成对应通知单
        Map<String, RepairReturnBomNotice> noticeMap = new HashMap<>();
        Map<String,List<OrderExcuteLineVo>> voMap = new HashMap<>();
        for(OrderExcuteLineVo orderExcuteVo : lines) {
            RepairReturnBomNotice notice = noticeMap.get(orderExcuteVo.getWhCode());
            if(notice == null) {
                notice = new RepairReturnBomNotice();

                notice.setBizOrderNo(order.getBizNo());
                notice.setNoticeDate(new Date());
                notice.setWhCode(orderExcuteVo.getWhCode());
                notice.setAccessType(OrderEnums.AccessType.IN.getCode());//出
                notice.setPickingType(NoticeStatusEnums.NoticeType.SPR_IN.getCode());//63备件退料入库
                notice.setNoticeStatus(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode());//直接确认
                noticeMap.put(orderExcuteVo.getWhCode(), notice);
                voMap.put(orderExcuteVo.getWhCode(), new ArrayList<OrderExcuteLineVo>());
            }
            voMap.get(orderExcuteVo.getWhCode()).add(orderExcuteVo);
        }
        // 生成通知单明细
        for(Map.Entry<String,RepairReturnBomNotice> entry : noticeMap.entrySet()) {
            RepairReturnBomNotice notice = entry.getValue();
            JpaUtil.save(notice);
            int lineNo = 0;
            for(OrderExcuteLineVo orderExcuteVo : voMap.get(entry.getKey())) {
                lineNo++;

                RepairReturnBomNoticeLine line = new RepairReturnBomNoticeLine();
                line.setOriginBizLineNo(orderExcuteVo.getBizOrderlineNo());
                line.setOriginBizNo(orderExcuteVo.getBizOrderNo());
                line.setItemCode(orderExcuteVo.getItemCode());
                line.setNoticeNo(notice.getNoticeNo());
                line.setQuantity(orderExcuteVo.getQuantity());

                line.setLineNo(lineNo+"");
                if (dbItemMap.containsKey(orderExcuteVo.getItemCode())){
                    Item item = dbItemMap.get(orderExcuteVo.getItemCode());
                    line.setItemName(item.getItemName());
                    line.setItemSpec(item.getItemSpec());
                    line.setUnitCode(item.getUnitCode());
                    line.setDrawingNo(item.getDrawingNo());
                }
                line.setLotNo(orderExcuteVo.getLotNo());
                line.setSubLotIndex(orderExcuteVo.getSubLotIndex());
                JpaUtil.save(line);
                //增加通知单对应的单号和行号
                orderExcuteVo.setNoticeNo(notice.getNoticeNo());
                orderExcuteVo.setNoticeLineNo(line.getLineNo());
            }
        }

        //生成 备件退料入库仓单
        for(Map.Entry<String,RepairReturnBomNotice> entry : noticeMap.entrySet()) {
            RepairReturnBomNotice notice = entry.getValue();
            int lineNo = 0;
            WarehouseOrder wo = null;
            for(OrderExcuteLineVo vo : voMap.get(entry.getKey())){
                lineNo++;
                if(wo == null){
                    wo = new WarehouseOrder();
                    wo.setAccessType(notice.getAccessType());
                    wo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                    wo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                    wo.setOrderStatus(OrderStatusEnums.OrderStatus.PLAN.getStatusCode());
                    wo.setOrderDate(new Date());
                    wo.setOriginBizNo(vo.getBizOrderNo());
                    wo.setWhCode(vo.getWhCode());
                    wo.setWoType(notice.getPickingType());
                    wo.setOriginNoticeNo(vo.getNoticeNo());//关联noticeno字段
                    JpaUtil.save(wo);
                }
                WarehouseOrderLine line = new WarehouseOrderLine();
                line.setWhCode(wo.getWhCode());
                line.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                Item item = dbItemMap.get(vo.getItemCode());
                line.setItemCode(vo.getItemCode());
                line.setItemGroupCode(item.getItemGroupCode());
                line.setItemName(item.getItemName());
                line.setItemSpec(item.getItemSpec());
                line.setUnitCode(item.getUnitCode());
                line.setDrawingNo(item.getDrawingNo());
                line.setQuantity(vo.getQuantity());
                line.setBizNo(wo.getBizNo());
                line.setLineNo(lineNo+"");
                line.setOriginBizNo(vo.getBizOrderNo());
                line.setOriginBizLineNo(vo.getBizOrderlineNo());
                line.setSort(vo.getSort());
                line.setOriginNoticeNo(vo.getNoticeNo());
                line.setOriginNoticeLineNo(vo.getNoticeLineNo());
                line.setLotNo(vo.getLotNo());
                line.setSubLotIndex(vo.getSubLotIndex());
                JpaUtil.save(line);
            }
        }
        return Result.OK();
    }

    @Override
    @Transactional
    public Result<?> submit(EquipmentRepair  tpmRepair) {
        EquipmentRepair bean = this.getById(EquipmentRepair.class,tpmRepair.getBizNo());
        if (bean == null) {
            return Result.error("实体未找到！");
        }
//        if (!(bean.getRepairStatus() == EquipmentEnums.RepairStatus.REPAIR.getCode()||bean.getRepairStatus() == EquipmentEnums.RepairStatus.REPORT.getCode())) {
//            return Result.error("仅维修中和待汇报状态允许提交操作！");
//        }
        if(!bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.REPORT.getCode())){
            return Result.error("仅待汇报状态允许提交操作！");
        }
        if (bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            return Result.error("单据已否决，不允许此操作！");
        }
        bean.setConsultContent(tpmRepair.getConsultContent());//咨询设备状态
        bean.setRepairHalt(tpmRepair.getRepairHalt());//维修停机
        bean.setPlanHalt(tpmRepair.getPlanHalt());//计划停机
        bean.setMaitainSummary(tpmRepair.getMaitainSummary());//任务过程总结描述
        bean.setFaultTypeCode(tpmRepair.getFaultTypeCode());//故障类型
        bean.setRepairAttachFile(tpmRepair.getAttachFile());//现场附件
        bean.setRepairPic(tpmRepair.getRepairPic());//现场照片
        bean.setMalfunctionReason(tpmRepair.getMalfunctionReason());//故障原因
        bean.setFaultPhenomenon(tpmRepair.getFaultPhenomenon());// 故障现象
        bean.setReportWorkingHours(tpmRepair.getReportWorkingHours());// 汇报时长
        bean.setFollowRepair(tpmRepair.getFollowRepair());//跟进维修内容


        //设置工单状态
        bean.setRepairStatus(EquipmentEnums.RepairStatus.EVA.getCode());//待评价
        if (bean.getActualEndDate() == null) { //当实际结束时间为空，这时为提交时间，当不为空时为完成时间
            bean.setActualEndDate(new Date());//这时的实际结束时间为提交时间
        }
//        if (StringUtils.equals(tpmRepair.getPlanHalt(), CommonEnums.YesNo.NO.getCode())) {//当计划停机为否的时候计算停机时长
            if (StringUtils.equals(bean.getApplyHalt(), CommonEnums.YesNo.YES.getCode()) && StringUtils.equals(tpmRepair.getRepairHalt(), CommonEnums.YesNo.YES.getCode())) {//是是
                long between = DateUtil.between(bean.getApplyTime(), bean.getActualEndDate(), DateUnit.MINUTE);
                if (between < 0) { //如果为负数转化为正数
                    between = -between;
                }
                bean.setFaultTime(between);
            }
            if (StringUtils.equals(bean.getApplyHalt(), CommonEnums.YesNo.YES.getCode()) && StringUtils.equals(tpmRepair.getRepairHalt(), CommonEnums.YesNo.NO.getCode())) {//是否
                long between = DateUtil.between(bean.getApplyTime(), bean.getActualStartDate(), DateUnit.MINUTE);
                if (between < 0) { //如果为负数转化为正数
                    between = -between;
                }
                bean.setFaultTime(between);
            }
            if (StringUtils.equals(bean.getApplyHalt(), CommonEnums.YesNo.NO.getCode()) && StringUtils.equals(tpmRepair.getRepairHalt(), CommonEnums.YesNo.YES.getCode())) {//否是
                long between = DateUtil.between(bean.getActualStartDate(), bean.getActualEndDate(), DateUnit.MINUTE);
                if (between < 0) { //如果为负数转化为正数
                    between = -between;
                }
                bean.setFaultTime(between);
            }
            if (StringUtils.equals(bean.getApplyHalt(), CommonEnums.YesNo.NO.getCode()) && StringUtils.equals(tpmRepair.getRepairHalt(), CommonEnums.YesNo.NO.getCode())) {//否否
                bean.setFaultTime(0L);
            }

//        } else {
//            bean.setFaultTime(0L);
//        }


        if (bean.getOverFlag()==null){
            bean.setOverFlag(0);
        }
        /*//设置是逾期原因
        if (tpmRepair.getOverFlag()!=null && tpmRepair.getOverFlag() == 1) {
            bean.setOverFlag(1);
            bean.setOverdueReason(tpmRepair.getOverdueReason());
        }*/

        if (bean.getWorkMinutes()==null){//可能会跳过完成步骤
            // 计算维修工时
            List<EquipmentRepairOperation> tpmRepairOperations = equipmentRepairOperationService.selectByMainId(bean.getBizNo());
            if (!CollectionUtils.isEmpty(tpmRepairOperations)) {
                Date beginStop = new Date();
                long totalWorkTime = DateUtil.between(bean.getActualStartDate(), bean.getActualEndDate(), DateUnit.MINUTE);
                if (totalWorkTime== 0){ //当维修时长小于一分钟时，让它等于1分钟。
                    totalWorkTime = 1;
                }
                long totalStopTime = 0;
                // 循环计算暂停时长
                for (int i = 0; i < tpmRepairOperations.size(); i++) {
                    if ("维修暂停".equals(tpmRepairOperations.get(i).getOperate())) {
                        beginStop = tpmRepairOperations.get(i).getOperateTime();
                    }
                    if ("维修暂停结束".equals(tpmRepairOperations.get(i).getOperate())) {
                        totalStopTime += DateUtil.between(beginStop,tpmRepairOperations.get(i).getOperateTime(), DateUnit.MINUTE);
                    }
                }
                bean.setWorkMinutes(totalWorkTime - totalStopTime);
                Long workMinutes = bean.getWorkMinutes();
                if (workMinutes>0){
                    String hourRation = bean.getHourRation();//计划工时（小时）
                    if (StringUtils.isNotBlank(hourRation)&&NumberUtil.isNumber(hourRation)) {//判断计划工时
                        BigDecimal hours = new BigDecimal(hourRation);
                        BigDecimal minutes = hours.multiply(new BigDecimal("60"));
                        if (workMinutes>minutes.longValue()){
                            bean.setOverFlag(1);//是否超时根据实际维修工时和计划工时比对
                            bean.setGoBeyondMinutes(workMinutes - minutes.longValue());//计算超时时间
                        }
                    }
                }
            }
        }
        bean.setTemporaryRepair(tpmRepair.getTemporaryRepair());
        this.update(bean);
        EquipmentRepair copyRepair = null;
        if (StringUtils.equals(CommonEnums.YesNo.YES.getCode(),tpmRepair.getTemporaryRepair())){//临时修复为是的情况
            copyRepair = new EquipmentRepair();
            //BeanReflectionUtils.copyProperties(copyRepair,bean);
            copyRepair.setApplyHalt(CommonEnums.YesNo.NO.getCode());
            copyRepair.setUseDeptId(bean.getUseDeptId());
            copyRepair.setBizNo(null);
            copyRepair.setOrderStatus(null);
            copyRepair.setBizType("FU");//工单类型 指定值为 计划维修工单
            copyRepair.setRepairStatus(EquipmentEnums.RepairStatus.APPLY.getCode());
            copyRepair.setTargetId(bean.getTargetId());
            copyRepair.setTargetName(bean.getTargetName());
            copyRepair.setTargetCode(bean.getTargetCode());
            copyRepair.setCodeAbc(bean.getCodeAbc());
            copyRepair.setEqpTypeId(bean.getEqpTypeId());
            copyRepair.setEqpTypeName(bean.getEqpTypeName());
            copyRepair.setFailureDate(bean.getFailureDate());
            copyRepair.setChkPersonPhone(bean.getChkPersonPhone());
            copyRepair.setChkPerson(bean.getChkPerson());
            copyRepair.setApplyId(userService.findByName(bean.getDistributePersonId()).getNickname());
            copyRepair.setApplyNo(bean.getApplyNo());
            copyRepair.setApplyTime(bean.getApplyTime());
            copyRepair.setExistingProblems(bean.getExistingProblems());
            copyRepair.setPic(bean.getPic());
            copyRepair.setAttachFile(bean.getAttachFile());
            copyRepair.setAddress(bean.getAddress());
            copyRepair.setIsUsable(bean.getIsUsable());
            copyRepair.setRepairPersonGroupCode(bean.getRepairPersonGroupCode());
            copyRepair.setEngineerPersonGroupCode(bean.getEngineerPersonGroupCode());
            copyRepair.setEmergencyFlag(bean.getEmergencyFlag());
            copyRepair.setSourceType(bean.getSourceType());
            copyRepair.setIsBottleneck(bean.getIsBottleneck());
            copyRepair.setSourceBizNo(bean.getBizNo());//记录源单单号
            copyRepair.setExistingProblems(bean.getFollowRepair());//将源工单的跟进维修内容生成为子工单的故障描述
            JpaUtil.save(copyRepair);//拷贝一个新的工单（新增初始状态）
            bean.setIsFUWork(CommonEnums.YesNo.YES.getCode());//原始工单生成个了跟进工单的标识
            this.update(bean);
        }
        //设置操作记录
        insertOperate(bean.getBizNo(), "维修提交", "维修提交");
        return Result.OK(copyRepair);//把拷备对象返回，用于前端跳转
    }

    @Override
    @Transactional
    public Result<?> change(EquipmentRepair tpmRepair) {
        EquipmentRepair bean = this.getById(EquipmentRepair.class,tpmRepair.getBizNo());
        if (bean == null || bean.getRepairStatus() != EquipmentEnums.RepairStatus.REPAIR.getCode()) {
            return Result.error("实体未找到或未开始维修状态！");
        }
        if (bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            return Result.error("单据已否决，不允许此操作！");
        }
        String orderStatus = tpmRepair.getOrderStatus();//执行中1、搁置2、等件3、委外4
        String orderStatusStr = "";
        bean.setOrderStatus(orderStatus);
        if (StringUtils.equals(orderStatus,EquipmentEnums.RepairOrderStatus.OUTSOURCE.getCode())){//委外情况
            bean.setDistributePersonId(tpmRepair.getDistributePersonId());//更换任务分配人为委外人
            orderStatusStr = "委外";
            if (bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.PAUSE.getCode())){
                bean.setRepairStatus(EquipmentEnums.RepairStatus.REPAIR.getCode());//单据恢复执行中
                insertOperate(bean.getBizNo(), "维修暂停结束", "维修暂停结束"+tpmRepair.getVetoReason()+"；由单据变更(委外)操作触发。");
            }
        }else if (StringUtils.equals(orderStatus,EquipmentEnums.RepairOrderStatus.WAIT.getCode())){//等件
            orderStatusStr = "等件";
            if (!bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.PAUSE.getCode())){
                bean.setRepairStatus(EquipmentEnums.RepairStatus.PAUSE.getCode());//单据暂停
                insertOperate(bean.getBizNo(), "维修暂停", orderStatusStr+"；由单据变更操作触发。");
            }
        }else if (StringUtils.equals(orderStatus,EquipmentEnums.RepairOrderStatus.PAUSE.getCode())){//搁置
            orderStatusStr = "搁置";
            if (!bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.PAUSE.getCode())){
                bean.setRepairStatus(EquipmentEnums.RepairStatus.PAUSE.getCode());//单据暂停
                insertOperate(bean.getBizNo(), "维修暂停", orderStatusStr+"；由单据变更操作触发。");
            }
        }else if (StringUtils.equals(orderStatus,EquipmentEnums.RepairOrderStatus.EXEC.getCode())){//委外情况
            orderStatusStr = "执行";
            if (bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.PAUSE.getCode())){
                bean.setRepairStatus(EquipmentEnums.RepairStatus.REPAIR.getCode());//单据恢复执行中
                insertOperate(bean.getBizNo(), "维修暂停结束", "维修暂停结束"+tpmRepair.getVetoReason()+"；由单据变更(执行)操作触发。");
            }
        }
        this.update(bean);
        //设置操作记录
        insertOperate(bean.getBizNo(), "维修变更-"+orderStatusStr, tpmRepair.getVetoReason());//与前端共识，此处用vetoReason传递变更原因字段
        return Result.OK();
    }

    @Override
    @Transactional
    public Result<?> check(EquipmentRepair tpmRepair ) {
        EquipmentRepair bean = this.getById(EquipmentRepair.class,tpmRepair.getBizNo());
        if (bean == null ) {
            return Result.error("实体未找到！");
        }
        if (bean.getRepairStatus() != EquipmentEnums.RepairStatus.CHECK.getCode()) {
            return Result.error("必须是待验收状态单据允许验收操作！");
        }
        if (bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.VETO.getCode())){
            return Result.error("单据已否决，不允许此操作！");
        }
        Integer isUsable = tpmRepair.getIsUsable();

        String checkResult = "";
        if (isUsable.equals(1)){
            bean.setRepairStatus(EquipmentEnums.RepairStatus.REPORT.getCode());
            checkResult = "已修复";
        }else{
            bean.setRepairStatus(EquipmentEnums.RepairStatus.REPAIR.getCode());
            String reason = tpmRepair.getRefuseReason();
            checkResult = "未修复，"+reason;

        }
        bean.setIsUsable(isUsable);
        bean.setCheckTime(new Date());
        bean.setCheckUser(SecurityUtils.getLoginUsername());
        this.update(bean);
        //设置操作记录
        insertOperate(bean.getBizNo(), "维修验收", "维修验收结果："+checkResult);
        return Result.OK();
    }

    @Override
    @Transactional
    public Result<List<EquipmentRepairEvaluateDetail>> saveDetailsAndEvaluta(List<EquipmentRepairEvaluateDetail> details) {
        if (details==null||details.isEmpty()){
            return Result.error("评价内容为空！");
        }
        JpaUtil.save(details);
        EquipmentRepair tpmRepair = this.getById(EquipmentRepair.class,details.get(0).getBizNo());
        if (tpmRepair == null ) {
            return Result.error("未找到维修任务实体对象");
        }
        if (!tpmRepair.getRepairStatus().equals(EquipmentEnums.RepairStatus.EVA.getCode()) ){
            return Result.error("仅待评价状态可以评价！");
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.SUPERVISOR.getCode());
        tpmRepair.setEvaluateDate(new Date());
        tpmRepair.setEvaluateUser(SecurityUtils.getLoginUser().getUsername());
        this.update(tpmRepair);

        //设置操作记录
        insertOperate(tpmRepair.getBizNo(), "评分", "评分");
        return Result.OK(details);
    }

    @Override
    @Transactional//关闭（异常）维修单
    public Result<?> shut(EquipmentRepair tpmRepair) {
        EquipmentRepair bean = this.getById(EquipmentRepair.class,tpmRepair.getBizNo());
        if (bean == null ) {
            return Result.error("实体未找到！");
        }
        if (bean.getRepairStatus() >= EquipmentEnums.RepairStatus.REPORT.getCode()
                &&bean.getRepairStatus() != EquipmentEnums.RepairStatus.PAUSE.getCode()) {
            return Result.error("必须是待汇报之前状态的单据允许验收操作！");
        }
        tpmRepair.setRepairStatus(EquipmentEnums.RepairStatus.SHUT.getCode());
        tpmRepair.setVetoReason(tpmRepair.getVetoReason());
        this.update(tpmRepair);

        insertOperate(tpmRepair.getBizNo(), "关闭", tpmRepair.getVetoReason());
        return Result.OK();
    }

//    @Override
//    @Transactional
//    public void goBeyondMinutes(Page<EquipmentRepair> pageResult ) {
////        List<EquipmentRepair> list = this.list(EquipmentRepair.class, criteria);
////        List<EquipmentRepair> repairs = new ArrayList<>();
//        // 获取当前日期
//        LocalDate today = LocalDate.now();
//        // 获取当前年份和月份
//        int currentYear = today.getYear();
//        Month currentMonth = today.getMonth();
//        for (EquipmentRepair repair : pageResult) {
//            // 获取维修单的创建日期
//            LocalDate createDate = repair.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//            // 获取维修单的创建年份和月份
//            int year = createDate.getYear();
//            Month month = createDate.getMonth();
//            // 判断是否上当月的数据
//            if (currentYear == year && currentMonth == month) {
//                Long workMinutes = repair.getWorkMinutes();//维修工时（分钟为单位）
//                if (workMinutes == null || workMinutes == 0) {
//                    continue;
//                } else {
//                    String hourRation1 = repair.getHourRation();//计划工时（小时）
//                    Long hour = Long.parseLong(hourRation1);
//                    Long hourRation = hour * 60;//计划工时（分钟）
//                    if (hourRation >= workMinutes) {
//                        continue;
//                    } else {
//                        repair.setGoBeyondMinutes(workMinutes - hourRation);
////                list.add(repair);
//                        this.update(repair);
//                    }
//                }
//            } else {
//                continue;
//            }
//        }
//    }



    /**
     * 当前登录用户协助的工单信息
     * @param criteria
     * @param page
     * @return
     */
    @Override
    @Transactional
    public Page<EquipmentRepair> userAssistedTickets(Criteria criteria, Pageable page) {
        //获取当前登录用户大的信息
//        User sysUser = SecurityUtils.getLoginUser();
//        String username = sysUser.getUsername();
        EquipmentRepair equipmentRepair = new EquipmentRepair();
        List<EquipmentRepairAssistants> list1 = equipmentRepairAssistantsService.userAssistance();
        if (list1 != null){
        List<EquipmentRepair> list2 = this.list(EquipmentRepair.class, criteria);
//        ArrayList<EquipmentRepairAssistants> equipmentRepairAssistants = new ArrayList<>();
        ArrayList<EquipmentRepair> equipmentRepairs = new ArrayList<>();
        for (EquipmentRepairAssistants Assistants : list1) {
            for (EquipmentRepair repair : list2) {
                if (Assistants.getBizNo().equals(repair.getBizNo())) {
                    equipmentRepairs.add(repair);
                }
            }
        }
        PageImpl<EquipmentRepair> equipment = new PageImpl<>(equipmentRepairs, page, equipmentRepairs.size());
        return equipment;
    }
        return new PageImpl<>(Collections.emptyList(), page, 0);
    }

    @Override
    @Transactional
    public List<Map<String, Object>> listTOP(Criteria criteria) {
        // 计算每个设备当月停机总时长
        String sql = "select\n" +
                     "TOP 10\n" +
                     "sum(ISNULL(fault_time_, 0)) as haltSum,\n" +
                     "mer.target_id_ as targetId,\n" +
                     "mer.target_name_ as targetName,\n" +
                     "mer.use_dept_id_ as useDeptId,\n" +
                     "mer.eqp_type_id_ as existingProblems\n" +
                     "from\n" +
                     "mb_erp_repair mer\n" +
                     "where\n" +
                     "MONTH(CREATE_TIME) = MONTH(GETDATE())\n" +
                     "AND mer.biz_type_= 'CI'\n" +
                     "group by\n" +
                     "mer.target_id_ ,\n" +
                     "mer.target_name_,\n" +
                     "mer.use_dept_id_,\n" +
                     "mer.eqp_type_id_\n" +
                     "order by\n" +
                     "sum(ISNULL(fault_time_, 0)) desc";
        List<Object[]> resultList = JpaUtil.nativeQuery(sql).getResultList();
        if (resultList == null){
            List<Map<String, Object>> list = new ArrayList<>();
            return list;
        }
        List<Map<String, Object>> arrayList = new ArrayList<>();// 存map中的数据
        Map<String, Dept> deptMap = new HashMap<>();
        for (Object[] row : resultList) {
            Map<String, Object> map = new HashMap<>();// 将数据转成键值格式对存入map
            BigInteger haltSum = (BigInteger) row[0];
            String targetId = (String) row[1];
            String targetName = (String) row[2];
            String useDeptId = (String) row[3];
            String existingProblems = (String) row[4];
            map.put("haltsum", haltSum);
            map.put("targetid", targetId);
            map.put("targetname", targetName);
            map.put("usedeptid", useDeptId);
            map.put("existingproblems", existingProblems);
            Dept dept = null;
            if (deptMap.containsKey(useDeptId)){
                dept = deptMap.get(useDeptId);
            }else{
                dept = JpaUtil.linq(Dept.class).equal("deptCode",useDeptId).findOne();
                deptMap.put(useDeptId, dept);
            }
            if (dept!=null){
                map.put("usedeptname", dept.getDeptName());
            }else{
                map.put("usedeptname", useDeptId);
            }
            arrayList.add(map);
        }
        return arrayList;
    }

    @Override
    @Transactional
    public Page<EquipmentRepair> getTheNumberOfFaultyDevices(Criteria criteria, Pageable page) {
        List<EquipmentRepair> list = this.list(EquipmentRepair.class, criteria);
        if (list.size() > 0){
        //使用set集合对targetId进行去重操作
        Set<String> targetIds = new HashSet<>();
        for (EquipmentRepair equipmentRepair : list) {
            targetIds.add(equipmentRepair.getTargetId());
        }
        List<EquipmentRepair> equipmentRepairs = new ArrayList<>();
        for (String targetId: targetIds){
            Optional<EquipmentRepair> repairOptional = list.stream()
                    .filter(repair -> repair.getTargetId().equals(targetId))
                    .findFirst();
            if (repairOptional.isPresent()) {
                equipmentRepairs.add(repairOptional.get());
            }
        }
        PageImpl<EquipmentRepair> equipmentRepairs1 = new PageImpl<>(equipmentRepairs, page, equipmentRepairs.size());
        return equipmentRepairs1;
        }
        return new PageImpl<>(Collections.emptyList(), page, 0);
    }


    @Override
    @Transactional
    public void getTheTotalDowntime() {
        Criteria criteria = Criteria.create();
        List<EquipmentRepair> list = this.list(EquipmentRepair.class, criteria);
        if (list != null) {
            // 获取当前日期
            LocalDate today = LocalDate.now();
            // 获取当前年份和月份
            int currentYear = today.getYear();
            Month currentMonth = today.getMonth();
            for (EquipmentRepair repair : list) {
                // 获取维修单的创建日期
                LocalDate createDate = repair.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                // 获取维修单的创建年份和月份
                int year = createDate.getYear();
                Month month = createDate.getMonth();
                // 判断是否上当月的数据
//                if (currentYear == year && currentMonth == month) {
                    if (repair.getRepairStatus().equals(EquipmentEnums.RepairStatus.REPAIR.getCode())||
                        repair.getRepairStatus().equals(EquipmentEnums.RepairStatus.APPLY.getCode())||
                        repair.getRepairStatus().equals(EquipmentEnums.RepairStatus.SEND.getCode())||
                            repair.getRepairStatus().equals(EquipmentEnums.RepairStatus.PAUSE.getCode())){
//                            ||repair.getRepairStatus().equals(EquipmentEnums.RepairStatus.REPORT.getCode())
//                            ||repair.getRepairStatus().equals(EquipmentEnums.RepairStatus.CHECK.getCode()) ){// 判断维修中，带汇报，待验收状态才进行下一步
                        if (repair.getApplyHalt() != null){
                            if (repair.getApplyHalt().equals(CommonEnums.YesNo.YES.getCode())){// 是否在申请时停机
                                // 走申请算法
//                                LocalDateTime actualStartDate = repair.getActualStartDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();// 维修完成时间
                                LocalDateTime createTime = repair.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();// 维修创建时间
                                LocalDateTime actualEndDate = LocalDateTime.now();//以当前时间为结束时间
                                Duration duration = Duration.between(createTime,actualEndDate);
//                                long hoursDiff = duration.toHours();// 小时
//                                long minutesDiff = duration.toMinutes() % 60; // 分钟
//                                long minutesDiffs = hoursDiff * 60;
//                                // 取整, 去掉-
//                                if (hoursDiff < 0 && minutesDiff < 0 && minutesDiffs < 0){
//                                    hoursDiff = -hoursDiff;
//                                    minutesDiff = -minutesDiff;
//                                    minutesDiffs = -minutesDiffs;
//                                }
                                long totalMinutes = duration.toMinutes(); // 总分钟数
                                // 取整, 去掉负号
                                if (totalMinutes < 0) {
                                    totalMinutes = -totalMinutes;
                                }
                                repair.setTotalDurationOfDowntime(totalMinutes);
                                this.update(repair);
                            }
//                            }else if (repair.getRepairHalt() != null){
//                                if (StringUtils.equals(repair.getRepairHalt(),CommonEnums.YesNo.YES.getCode()) && StringUtils.equals(repair.getPlanHalt(), CommonEnums.YesNo.NO.getCode())){// 是否在执行时停机,和否计划停机
//                                    // 走执行算法
//                                    LocalDateTime actualStart = repair.getActualStartDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();// 维修开始时间
////                                  LocalDateTime actualEnd = repair.getActualEndDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();// 维修完成时间
//                                    LocalDateTime actualEndDate = LocalDateTime.now();//以当前时间为结束时间
//                                    Duration between = Duration.between(actualStart, actualEndDate);
//                                    long hours = between.toHours();// 小时
//                                    long minutes = between.toMinutes() % 60;// 分钟
//                                    long minute = hours * 60;
//                                    // 取整, 去掉-
//                                    if (hours < 0 && minutes < 0 && minute < 0){
//                                        hours = -hours;
//                                        minutes = -minutes;
//                                        minute = -minute;
//                                    }
//                                    repair.setTotalDurationOfDowntime(minute);
//                                    this.update(repair);
//                                }
//                            }
                        }
                    }else {
                        continue;// 不在维修中,(跳过)不计算
                    }
//                }
            }
        }
    }

    @Override
    @Transactional//主管确认
    public Result<?> confirm(EquipmentRepair equipmentRepair) {//supervisor
        EquipmentRepair bean = this.getById(EquipmentRepair.class,equipmentRepair.getBizNo());
        if (bean == null) {
            return Result.error("实体未找到！");
        }
        if (bean.getRepairStatus() != EquipmentEnums.RepairStatus.SUPERVISOR.getCode()) {
            return Result.error("必须是维修主管确认状态的单据允许该操作！");
        }
        bean.setRepairStatus(EquipmentEnums.RepairStatus.ZIPING.getCode());
        this.update(bean);
        //设置操作记录
        insertOperate(bean.getBizNo(), "维修主管审核确认", "维修主管审核确认");//此处 操作节点 名称不能随便更改，如果修改，注意是否有视图根据该节点日志记录 查询对应的操作人、操作时间
        return Result.OK(bean);
    }

    @Override
    @Transactional
    public EquipmentRepair isEvaluate(EquipmentRepair equipmentRepair) {
        EquipmentRepair bean = this.getById(EquipmentRepair.class,equipmentRepair.getBizNo());
        if (!bean.getRepairStatus().equals(EquipmentEnums.RepairStatus.EVA.getCode())) {
            throw new MBootException("不是待评价状态的单据不允许该操作！");
        }
        Integer isEvaluate = equipmentRepair.getIsEvaluate();
//        //评价通过
//        if (isEvaluate.equals(CommonEnums.YesNo.YES.getCode())) {
//            bean.setIsEvaluate(isEvaluate);
//            this.update(bean);
//
//            //添加操作记录
//            insertOperate(equipmentRepair.getBizNo(), "维修评价", "评价通过");
//        //评价未通过
//        }else
        if (isEvaluate==0){
            bean.setIsEvaluate(isEvaluate);
            bean.setRepairStatus(EquipmentEnums.RepairStatus.REPORT.getCode());
            bean.setNoEvaluateReason(StrUtil.addPrefixIfNot(equipmentRepair.getNoEvaluateReason(), "评价退回："));
//            bean.setNoEvaluateReason(equipmentRepair.getNoEvaluateReason());
            this.update(bean);


            //添加操作记录
            //操作节点名称 --评价退回--，请不要改，后台视图那里有校验
            insertOperate(equipmentRepair.getBizNo(), "评价退回", bean.getNoEvaluateReason());

        }
        String[] toUsers = {bean.getDistributePersonId()};
        //发送站内信
        messageService.sendMessage(channelCodes,SecurityUtils.getLoginUsername(),toUsers,"维修工单评价被退回","维修工单【"+bean.getBizNo()+"】评价被退回，退回原因："+equipmentRepair.getNoEvaluateReason()+"。请知悉！具体信息请在工单详情页面查看。");

        return bean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAdminRepairById(EquipmentRepair equipmentRepair) {
        //设置申请人工号

        //User sysUser = userService.findByName(equipmentRepair.getApplyId());
        //equipmentRepair.setApplyNo(sysUser.getUsername());
        //区域时设置区域名称，编码
        EquipmentRepair one = this.getById(EquipmentRepair.class, equipmentRepair.getBizNo());
        if ("area".equals(equipmentRepair.getTargetType())) {
            EquipmentArea equipmentArea = equipmentAreaService.getById(EquipmentArea.class, equipmentRepair.getTargetId());
            //获取该区域的上级区域的名称
            String name = equipmentAreaService.getParentAllNameByPid(equipmentArea.getPid());
            equipmentRepair.setTargetName(name + "/" + equipmentArea.getAreaName());
            equipmentRepair.setTargetCode(equipmentArea.getAreaCode());
            one.setTargetName(equipmentRepair.getTargetName());
            one.setTargetCode(equipmentRepair.getTargetCode());
        }
        //选择为设备时调整设备状态 为40（维保中）
        /*if ("eqp".equals(equipmentRepair.getTargetType())) {
            EquipmentEqpBasics eqpBasics = equipmentService.getById(EquipmentEqpBasics.class, equipmentRepair.getTargetId());
            //更新上一条记录的下一个操作时间
            equipmentEqpStatusRecordsService.saveRecordAndUpdatePreRecord(eqpBasics,40,"设备维修");
            //变更设备状态
            eqpBasics.setStatus(40);
            equipmentService.update(eqpBasics);
            equipmentRepair.setTargetCode(eqpBasics.getEqpCode());
            equipmentRepair.setTargetName(eqpBasics.getEqpName());

        }*/
        one.setTargetId(equipmentRepair.getTargetId());
        one.setBizType(equipmentRepair.getBizType());
        one.setApplyHalt(equipmentRepair.getApplyHalt());
        one.setFailureDate(equipmentRepair.getFailureDate());
        one.setApplyId(equipmentRepair.getApplyId());
        one.setChkPersonPhone(equipmentRepair.getChkPersonPhone());
        one.setExistingProblems(equipmentRepair.getExistingProblems());
        one.setPic(equipmentRepair.getPic());
        one.setAttachFile(equipmentRepair.getAttachFile());
        one.setRepairHalt(equipmentRepair.getRepairHalt());
        if (one.getTemporaryRepair()!=null){
            if (one.getTemporaryRepair().equals(CommonEnums.YesNo.NO.getCode())){//当源数据临时修复为是时，不可在修改为否,当为否的时候可以修改
                one.setTemporaryRepair(equipmentRepair.getTemporaryRepair());//临时修复字段
            }
        }

        one.setPlanHalt(equipmentRepair.getPlanHalt());
        one.setFaultPhenomenon(equipmentRepair.getFaultPhenomenon());
        one.setFollowRepair(equipmentRepair.getFollowRepair());
        one.setMaitainSummary(equipmentRepair.getMaitainSummary());
        one.setMalfunctionReason(equipmentRepair.getMalfunctionReason());
        one.setDistributePersonId(equipmentRepair.getDistributePersonId());
        one.setReportWorkingHours(equipmentRepair.getReportWorkingHours());
        one.setFaultTime(equipmentRepair.getFaultTime());
        one.setFaultTypeCode(equipmentRepair.getFaultTypeCode());
        one.setRepairAttachFile(equipmentRepair.getRepairAttachFile());
        one.setRepairPic(equipmentRepair.getRepairPic());
        one.setFollowRepair(equipmentRepair.getFollowRepair());
        one.setIsBottleneck(equipmentRepair.getIsBottleneck());
        this.update(one);

        if (one.getIsFUWork().equals(CommonEnums.YesNo.NO.getCode())) {
            EquipmentRepair copyRepair = null;
            if (StringUtils.equals(CommonEnums.YesNo.YES.getCode(), one.getTemporaryRepair())) {//临时修复为是的情况
                copyRepair = new EquipmentRepair();
                //BeanReflectionUtils.copyProperties(copyRepair,bean);
                copyRepair.setBizNo(null);
                copyRepair.setOrderStatus(null);
                copyRepair.setBizType("FU");//工单类型 指定值为 计划维修工单
                copyRepair.setRepairStatus(EquipmentEnums.RepairStatus.APPLY.getCode());
                copyRepair.setTargetId(one.getTargetId());
                copyRepair.setTargetName(one.getTargetName());
                copyRepair.setTargetCode(one.getTargetCode());
                copyRepair.setCodeAbc(one.getCodeAbc());
                copyRepair.setEqpTypeId(one.getEqpTypeId());
                copyRepair.setEqpTypeName(one.getEqpTypeName());
                copyRepair.setFailureDate(one.getFailureDate());
                copyRepair.setChkPersonPhone(one.getChkPersonPhone());
                copyRepair.setChkPerson(one.getChkPerson());
                copyRepair.setApplyId(userService.findByName(one.getDistributePersonId()).getNickname());
                copyRepair.setApplyNo(one.getApplyNo());
                copyRepair.setApplyTime(one.getApplyTime());
                copyRepair.setExistingProblems(one.getExistingProblems());
                copyRepair.setPic(one.getPic());
                copyRepair.setAttachFile(one.getAttachFile());
                copyRepair.setAddress(one.getAddress());
                copyRepair.setIsUsable(one.getIsUsable());
                copyRepair.setRepairPersonGroupCode(one.getRepairPersonGroupCode());
                copyRepair.setEngineerPersonGroupCode(one.getEngineerPersonGroupCode());
                copyRepair.setEmergencyFlag(one.getEmergencyFlag());
                copyRepair.setSourceType(one.getSourceType());
                copyRepair.setIsBottleneck(one.getIsBottleneck());
                copyRepair.setSourceBizNo(one.getBizNo());//记录源单单号
                copyRepair.setExistingProblems(one.getFollowRepair());//将源工单的跟进维修内容生成为子工单的故障描述
                JpaUtil.save(copyRepair);//拷贝一个新的工单（新增初始状态）
                one.setIsFUWork(CommonEnums.YesNo.YES.getCode());//原始工单生成个了跟进工单的标识
                this.update(one);
            }
        }

        //判断是否修改了是否停机
        EquipmentRepair bean = this.getById(EquipmentRepair.class, equipmentRepair.getBizNo());
        if (StringUtils.equals(bean.getApplyHalt(), CommonEnums.YesNo.YES.getCode()) && StringUtils.equals(bean.getRepairHalt(), CommonEnums.YesNo.YES.getCode())) {//是是
            long between = DateUtil.between(bean.getApplyTime(), bean.getActualEndDate(), DateUnit.MINUTE);
            if (between < 0) { //如果为负数转化为正数
                between = -between;
            }
            bean.setFaultTime(between);
        }
        if (StringUtils.equals(bean.getApplyHalt(), CommonEnums.YesNo.YES.getCode()) && StringUtils.equals(bean.getRepairHalt(), CommonEnums.YesNo.NO.getCode())) {//是否
            long between = DateUtil.between(bean.getApplyTime(), bean.getActualStartDate(), DateUnit.MINUTE);
            if (between < 0) { //如果为负数转化为正数
                between = -between;
            }
            bean.setFaultTime(between);
        }
        if (StringUtils.equals(bean.getApplyHalt(), CommonEnums.YesNo.NO.getCode()) && StringUtils.equals(bean.getRepairHalt(), CommonEnums.YesNo.YES.getCode())) {//否是
            long between = DateUtil.between(bean.getActualStartDate(), bean.getActualEndDate(), DateUnit.MINUTE);
            if (between < 0) { //如果为负数转化为正数
                between = -between;
            }
            bean.setFaultTime(between);
        }
        if (StringUtils.equals(bean.getApplyHalt(), CommonEnums.YesNo.NO.getCode()) && StringUtils.equals(bean.getRepairHalt(), CommonEnums.YesNo.NO.getCode())) {//否否
            bean.setFaultTime(0L);
        }
        this.update(bean);
    }

}
